package algorithm.leetcode;

import algorithm.templates.ListNode;

/**
 * @author wuwen
 * @since 2023/12/6
 */
public class NO2_两数相加 {

    class PerformanceSolution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            // 在每一个子位上进行相加，然后进位
            int carry = 0;
            ListNode dummy = new ListNode(-1);
            ListNode cur = dummy;

            while (l1 != null || l2 != null || carry != 0) {
                int sum = carry;
                if (l1 != null) {
                    sum += l1.val;
                    l1 = l1.next;
                }
                if (l2 != null) {
                    sum += l2.val;
                    l2 = l2.next;
                }
                carry = sum / 10;
                cur.next = new ListNode(sum % 10);
                cur = cur.next;
            }
            return dummy.next;
        }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int sum, carry = 0;
            ListNode head = null, temp = null;
            int active, passive;
            while (l1 != null || l2 != null) {
                // reset operator number
                active = passive = 0;
                if (l1 != null) {
                    active = l1.val;
                    l1 = l1.next;
                }
                if (l2 != null) {
                    passive = l2.val;
                    l2 = l2.next;
                }
                // calculate
                sum = active + passive + carry;
                carry = sum / 10;
                sum %= 10;
                // begin alloc new list memory ,and attach new node
                if (head == null) {
                    head = new ListNode(sum);
                    temp = head;
                } else {
                    ListNode next = new ListNode(sum);
                    temp.next = next;
                    temp = next;
                }
            }
            if (carry != 0) {
                temp.next = new ListNode(carry);
            }
            return head;
        }
    }
}